package com.sunl.mall.ali.mq.api.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.sunl.mall.ali.mq.model.RocketMqMessageBody;
import com.sunl.mall.ali.mq.model.RocketMqMessageContext;
import com.sunl.mall.ali.mq.serializer.RocketMqDeserializer;
import com.sunl.mall.common.api.topic.MqTopic;

import java.util.List;


public interface RocketMqBatchMessageListener<T> extends RocketMqDeserializer<T> {

    /**
     * 处理消息
     *
     * @param body    反序列化后的消息体
     * @param context 消息上下文
     * @return Action 接收到消息后执行的操作
     * @throws Exception exception
     */
    default Action call(RocketMqMessageBody<T> body, RocketMqMessageContext context) throws Exception {
        return Action.CommitMessage;
    }

    /**
     * 批量处理消息
     * <p>
     * 有一条处理失败了则全部重试（下游必须保证接口幂等）
     *
     * @param records  反序列化后的消息体
     * @param contexts 消息上下文
     * @return Action 接收到消息后执行的操作
     * @throws Exception exception
     */
    default Action call(List<RocketMqMessageBody<T>> records, List<RocketMqMessageContext> contexts) throws Exception {
        for (int i = 0; i < records.size(); i++) {
            Action action = call(records.get(i), contexts.get(i));
            if (action != Action.CommitMessage) {
                return action;
            }
        }
        return Action.CommitMessage;
    }

    /**
     * 订阅主题
     *
     * @return com.sunl.mall.common.api.topic not null
     */
    MqTopic subscribe();
}